<template>
  <a-row>
    <a-col class="leftCol" :span="8">
      <a-card class="card" :loading="departCardloading" :bordered="true">
        <a-row>
          <a-col :span="24">
            <div class="table-operations">
              <a-button ghost value="small" type="primary" icon="plus" @click="handlePositAdd()">添加</a-button>
              <a-button ghost value="small" type="primary" icon="edit" @click="handlePositEdit()">修改</a-button>
              <a-button value="small" type="danger" icon="close" @click="handlePositDel()">删除</a-button>
            </div>
            <a-divider orientation="left"></a-divider>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <div class="tree-operations">
              <a-directory-tree
                :loadData="onLoadData"
                :treeData="treeData"
                :selectedKeys="selectedKeys"
                @select="onSelect"
                @expand="onExpand">
              </a-directory-tree>
            </div>
          </a-col>
        </a-row>
      </a-card>
    </a-col>
    <a-col :span="16">
      <a-card :loading="personCardloading" class="card" :bordered="true">
        <div>
          <div class="table-operations">
            <a-button value="small" type="primary" icon="user-add" @click="handlePositMembers()">添加人员</a-button>
            <a-input-search placeholder="搜索当前部门人员" style="width: 230px" @search="onSearch" enterButton />
          </div>
          <a-table
            :columns="departMembersColumns"
            :rowKey="record => record.rdp.pid"
            :dataSource="departMembersData"
            :pagination="paginations"
            @change="onChange"
          >
            <span slot="action" slot-scope="text, record">
              <template>
                <a @click="handlePersonEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a @click="handlePositPersonRemove(record)">移出</a>
              </template>
            </span>
          </a-table>
        </div>
        <posit-members-modal ref="PositMembersModal" @close="handlePositMembersModalClose" />
        <posit-modal ref="PositModal" @close="handlePositModalClose" />
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import PositModal from './modules/PositModal'
import PositMembersModal from './modules/PositMembersModal'
import PersonModal from './modules/PersonModal'
import AccountModal from './modules/AccountModal'
import { getDepartByParentPositPid, delPositBySysSeqOrPid, getPositByParentPositPid } from './posit'
import { getPositMembersByDeptPid, getPositMembersCountByDeptPid, delPositMemberBySysSeq } from './person'
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'

export default {
  name: 'Position',
  components: {
    PositModal,
    PositMembersModal,
    PersonModal,
    AccountModal
  },
  data () {
    return {
      // 中文
      locale: zhCN,
      departCardloading: true,
      personCardloading: true,
      treeData: [], // 部门树
      selectedNodes: [{}],
      selectedKeys: ['org'], // 选中的部门
      departMembersData: [], // 部门人员
      paginations: { // 部门人员表分页控件
        showSizeChanger: true,
        showQuickJumper: true,
        // defaultCurrent: 1,
        total: 0,
        pageSize: 10,
        current: 1
      },
      departMembersColumns: [
        {
          title: '工号',
          dataIndex: 'rop.empno'
          // sorter: true
        },
        {
          title: '姓名',
          dataIndex: 'person.personName'
          // sorter: true
          // needTotal: true,
          // customRender: (text) => text + ' 次'
        },
        {
          title: '性别',
          dataIndex: 'person.personsex',
          customRender: function (text) {
            if (text === '1') {
              return '男'
            } else if (text === '0') {
              return '女'
            } else {
              return text
            }
          }
        },
        {
          title: '出生日期',
          dataIndex: 'personBirthday'
        },
        {
          title: '联系电话',
          dataIndex: 'person.personMobile'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' }
        }
      ]

    }
  },
  created () {
    this.getTopDepartment()
  },
  mounted () {
  },
  methods: {
    // 显示总数
    // 总条数
    showTotal (total) {
      return `共 ${total} 条`
    },
    // 部门点击按钮
    onSelect (selectedKeys, info) {
      this.personCardloading = true
      // 加载子节点
      const treeNode = info.node
      getDepartByParentPositPid(treeNode.dataRef.key, {})
        .then(res => {
          if (res) {
            if (res.code !== 'C0') {
              treeNode.dataRef.children = []
              var departments = res.data
              for (var i = 0; i < departments.length; i++) {
                var tn = {
                  title: departments[i].departName,
                  key: departments[i].pid
                }
                treeNode.dataRef.children.push(tn)
              }
              this.treeData = [...this.treeData]
            }
          }
        })
      // 结束
      this.selectedNodes = [info] // 节点单选
      if (this.selectedKeys !== [selectedKeys[0]]) {
        this.selectedKeys = [selectedKeys[0]] // 节点单选
        this.paginations.current = 1
      }
      this.getMembersByDeptPid(this.selectedKeys[0])
    },
    // 初始顶级部门
    getTopDepartment () {
      this.treeData = []
      new Promise((resolve) => {
        resolve(getDepartByParentPositPid('org', {}))
      }).then(res => {
        new Promise((resolve) => {
          // resolve(function () {
          console.log(res)
          if (res.code === 'C1') {
            var departments = res.data
            for (var i = 0; i < departments.length; i++) {
              // if (i === 0) {
              //   this.selectedKeys = [departments[i].pid]
              // }
              var tn = {
                title: departments[i].departName,
                key: departments[i].pid
              }
              this.treeData.push(tn)
              console.log('treeData', this.treeData)
            }
            // if (this.treeData) {
            //   this.treeData.selectedKeys = { [0] }
            // }
          }
          this.departCardloading = false
          resolve()
          // })
        }).then(() => {
          if (this.selectedKeys) {
            this.getMembersByDeptPid(this.selectedKeys[0])
          }
        })
      }).catch(() => {
        // Do something
      }).finally(() => {
      })
    },
    // 部门树展开按钮
    onExpand () {
      // console.log('Trigger Expand')
    },
    // 部门树加载节点
    onLoadData (treeNode) {
      console.log(treeNode)
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        new Promise(resolve => { 
          getPositByDeptPid(treeNode.dataRef.key, {})
          .then(res => {
            if (res && res.code === 'C1') {
              treeNode.dataRef.children = []
                var departments = res.data
                for (var i = 0; i < departments.length; i++) {
                  var tn = {
                    title: departments[i].departName,
                    key: departments[i].pid
                  }
                  treeNode.dataRef.children.push(tn)
                }
                this.treeData = [...this.treeData]
            }
          })
          resolve()
        }).then(() => {
           getDepartByParentPositPid(treeNode.dataRef.key, {})
            .then(res => {
              if (res) {
                if (res.code === 'C1') {
                  treeNode.dataRef.children = []
                  var departments = res.data
                  for (var i = 0; i < departments.length; i++) {
                    var tn = {
                      title: departments[i].departName,
                      key: departments[i].pid
                    }
                    treeNode.dataRef.children.push(tn)
                  }
                  this.treeData = [...this.treeData]
                }
              }
            })
        })
        
        
       
        resolve()
      })
    },
    // 查询部门人员
    getPositMembers () {

    },
    // 搜索人员
    onSearch () {
    },
    // 部门人与管理
    handlePositMembers () {
      this.$refs.PositMembersModal.showModal(this.selectedKeys[0])
    },
    // 部门人员翻页等
    onChange (params) {
      this.paginations.current = params.current
      this.paginations.pageSize = params.pageSize
      this.getMembersByDeptPid(this.selectedKeys[0])
    },
    // 编辑人员信息
    handlePersonEdit (record) {
      this.$refs.PersonModal.showEditModal(record.person.pid, record.rop.sysSeq, record.rop.pid, record.rop.empno)
    },
    // 编辑人员信息后回调
    handlePersonModalOk () {
      this.getMembersByDeptPid(this.selectedKeys[0])
    },
    // 打开账号管理界面
    handlePersonAccentManager (record) {
      this.$refs.AccountModal.showModal(record.person.pid)
    },
    // 从部门删除人员
    handlePositPersonRemove (record) {
      const _this = this
      if (record.rdp.sysSeq) {
        let personName = ''
        let departName = ''
        if (record.person && record.person.personName) {
          personName = record.person.personName
        }
        if (record.posit && record.posit.departName) {
          departName = record.posit.departName
        }
        _this.$confirm({
          title: '确定移除?',
          content: '该操作将人员 ' + personName + ' 从' + departName + '部门移除',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          // onCancel () {
          // }
          onOk () {
            //  new Promise((resolve) => {
            //   console.log('res')
            //   resolve(delPositMemberBySysSeq(record.rdp.sysSeq, {}))
            // }).then(res => {
            //   if (res.code === 'C1') {
            //     _this.$message.success('已从该部门移除', 3)
            //     _this.getMembersByDeptPid(_this.selectedKeys[0])
            //     // console.log(this.treeData)
            //   }
            // })
            delPositMemberBySysSeq(record.rdp.sysSeq, {})
              .then(res => {
                if (res.code === 'C1') {
                  _this.$message.success('已从该部门移除', 3)
                  _this.getMembersByDeptPid(_this.selectedKeys[0])
                  // console.log(this.treeData)
                }
              })
          }
        })
      }
    },
    // 新增部门按钮
    handlePositAdd () {
      const parentDeptPid = this.selectedKeys[0]
      this.$refs.PositModal.showAddModal(parentDeptPid)
    },
    // 编辑部门按钮
    handlePositEdit () {
      const positPid = this.selectedKeys[0]
      this.$refs.PositModal.showEditModal(positPid)
    },
    // 删除部门按钮
    handlePositDel () {
      const _this = this
      const positPid = _this.selectedKeys[0]
      if (positPid) {
        _this.$confirm({
          title: '确定移除?',
          content: '该操作将删除职位及相关数据,且不可恢复,是否继续删除',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          // onCancel () {
          // }
          onOk () {
            const department = {
              pid: positPid
            }
            delPositBySysSeqOrPid(department, {}).then(res => {
              if (res.code === 'C1') {
                _this.$message.success('该职位及相关数据已删除除', 3)
                _this.getTopPositment()
                // _this.getMembersByDeptPid( _this.selectedKeys[0])
              }
            })
          }
        })
      }
    },
    // 部门编辑按钮关闭回调
    handlePositModalClose () {
      if (this.selectedKeys[0] !== 'org') {
        this.onSelect(this.selectedKeys, this.selectedNodes[0])
      } else {
        this.getTopPositment()
      }
    },
    // 部门成员管理模态窗口关闭回调
    handlePositMembersModalClose () {
      this.getMembersByDeptPid(this.selectedKeys[0])
    },
    // 查询部门下人员
    getMembersByDeptPid (positPid) {
      if (positPid) {
        getPositMembersByDeptPid(positPid, {}, this.paginations.pageSize, this.paginations.current)
          .then(res => {
            this.departMembersData = res.data
            this.personCardloading = false
          })
        getPositMembersCountByDeptPid(positPid, {})
          .then(res => {
            this.paginations.total = res.data
            this.paginations.showTotal = this.showTotal
          })
      }
    }

  }
}
</script>

<style lang="less">
  .card {
    margin: 10px;
    margin-top: 0px;
    min-height:300px;
  }
  .table-operations {
    margin-bottom: 10px;
    text-align: right;
  }
  .table-operations > button {
    margin-right: 10px;
    // text-align: right;
  }
  .table-operations > input {
    margin-left: 10px;
    // text-align: right;
  }
  .tree-operations {
    margin-bottom: 16px;
    overflow: auto;
    max-height: 500px;
    // float: right;
  }
  .leftCol {
    min-width:300px;
  }
</style>
